<template>
  <div class="user-management">
    <el-card class="user-card" shadow="always">
      <div class="header-container">
        <span class="title">用户管理</span>
      </div>

      <el-table
        :data="userList"
        border
        stripe
        highlight-current-row
        class="user-table"
        v-loading="loading"
        element-loading-text="数据加载中"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="loginName" label="用户名" min-width="120" />
        <el-table-column prop="userName" label="真实姓名" min-width="100" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="mobile" label="手机号" min-width="150" />
        <el-table-column label="角色" align="center" min-width="80">
          <template #default="scope">
            <el-tag :type="scope.row.type === 1 ? 'warning' : 'info'">
              {{ scope.row.type === 1 ? "管理员" : "普通用户" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" min-width="80">
          <template #default="scope">
            <el-tag :type="scope.row.isdel === 1 ? 'danger' : 'success'">
              {{ scope.row.isdel === 1 ? "已删除" : "正常" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="180">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="openEditDialog(scope.row)"
              class="operation-btn"
              :disabled="scope.row.isdel === 1"
            >
              修改
            </el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              class="operation-btn"
              :disabled="scope.row.type === 1 || scope.row.isdel === 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        @current-change="handlePageChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        background
      />
    </el-card>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户信息"
      width="500px"
      append-to-body
      :visible.sync="editDialogVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
        class="form-container"
      >
        <el-form-item label="用户名" prop="loginName">
          <el-input v-model="editForm.loginName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="userName">
          <el-input
            v-model="editForm.userName"
            placeholder="请输入真实姓名"
            disabled
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="editForm.password"
            type="password"
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="editForm.email"
            placeholder="请输入邮箱"
            type="email"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="editForm.mobile"
            placeholder="请输入手机号"
            pattern="^1[3-9]\d{9}$"
          />
        </el-form-item>
        <el-form-item label="状态" prop="isdel">
          <el-switch
            v-model="editForm.isdel"
            active-value="0"
            inactive-value="1"
            active-text="正常"
            inactive-text="已删除"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userList: [],
      pageNum: 1,
      pageSize: 10,
      totalCount: 0,
      editDialogVisible: false,
      editForm: {
        id: null,
        loginName: "",
        userName: "",
        password: "",
        email: "",
        mobile: "",
        type: 2, // 默认为普通用户
        isdel: 0, // 默认为正常状态
      },
      editFormRules: {
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
        userName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "邮箱格式不正确", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: "^1[3-9]\\d{9}$", // 修复正则表达式
            message: "手机号格式不正确",
            trigger: "blur",
          },
        ],
      },
      loading: false,
    };
  },

  mounted() {
    this.fetchUserList();
  },

  methods: {
    async fetchUserList() {
      this.loading = true;
      try {
        const response = await this.$axios.get("/easybuy/user/showUser", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            // 移除isDel过滤，显示所有用户
          },
        });
        if (response.data.code === "200") {
          this.userList = response.data.pageInfo.list || [];
          this.totalCount = response.data.pageInfo.total || 0;
        } else {
          this.$message.error(response.data.message || "获取用户列表失败");
        }
      } catch (error) {
        console.error("获取用户列表失败:", error);
        this.$message.error("网络请求失败，请重试");
      } finally {
        this.loading = false;
      }
    },

    handlePageChange(page) {
      this.pageNum = page;
      this.fetchUserList();
    },

    openEditDialog(row) {
      this.editDialogVisible = true;
      this.editForm = { ...row, password: "" }; // 清空密码
    },

    async submitEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return;

        try {
          // 构建提交数据
          const formData = {
            id: this.editForm.id,
            loginName: this.editForm.loginName,
            userName: this.editForm.userName,
            password: this.editForm.password || undefined, // 可选更新
            email: this.editForm.email,
            mobile: this.editForm.mobile,
            isdel: parseInt(this.editForm.isdel), // 确保是数字类型
          };

          const response = await this.$axios.post(
            "/easybuy/user/updateUser",
            formData
          );

          if (response.data.code === "200") {
            this.$message.success("用户信息修改成功");
            this.editDialogVisible = false;
            this.fetchUserList();
          } else {
            this.$message.error(
              response.data.message || "修改失败，请检查信息"
            );
          }
        } catch (error) {
          console.error("修改用户失败:", error);
          this.$message.error("网络错误，请稍后重试");
        }
      });
    },

    handleDelete(row) {
      if (row.type === 1) {
        this.$message.warning("不能删除管理员用户");
        return;
      }

      this.$confirm("确定要标记为删除吗？", "警告", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "danger",
      }).then(async () => {
        try {
          const response = await this.$axios.post("/easybuy/user/deleteUser", {
            id: row.id,
            isdel: 1,
          });

          if (response.data.code === "200") {
            this.$message.success("用户已标记为删除");
            this.fetchUserList();
          } else {
            this.$message.error(response.data.message || "删除失败");
          }
        } catch (error) {
          console.error("删除用户失败:", error);
          this.$message.error("网络错误，请稍后重试");
        }
      });
    },

    handleClose() {
      this.$refs.editForm.resetFields();
      this.editDialogVisible = false;
    },
  },
};
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #f8f9fa;
}

.user-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.header-container {
  padding: 20px;
  border-bottom: 1px solid #ebedf0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 1.25rem;
  font-weight: 500;
  color: #2c3e50;
}

.user-table {
  margin-top: 20px;
  font-size: 0.9rem;
}

.operation-btn {
  margin-right: 8px;
  padding: 4px 12px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.form-container {
  padding: 20px;
}

.el-dialog__header {
  padding: 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebedf0;
}

.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-input__inner {
  border-radius: 6px;
}

/* 增强标签样式 */
.el-tag {
  border-radius: 4px;
  padding: 0 8px;
  font-size: 12px;
}
</style>